package com.thinkingcoder.tcrpc.core.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MethodUtils {
    public static boolean checkLocalMethod(final String methodName) {
        // 本地方法不代理
        return switch (methodName) {
            case "toString", "hashCode", "notifyAll", "equals", "wait", "getClass", "notify" -> true;
            default -> false;
        };

    }

    public static boolean checkLocalMethod(final Method method) {
        return method.getDeclaringClass().equals(Object.class);
    }

    public static String methodSign(Method method) {
        StringBuilder sb = new StringBuilder(method.getName());

        sb.append("@").append(method.getParameterCount());

        Arrays.stream(method.getParameterTypes()).forEach(paramTypeTemp -> {
            sb.append("_").append(paramTypeTemp.getCanonicalName());
        });
        return sb.toString();
    }

    public static List<Field> findAnnotatedField(Class<?> beanClass, Class<? extends Annotation> annotationClass) {
        List<Field> result = new ArrayList<>();

        while (beanClass != null) {
            Field[] fields = beanClass.getDeclaredFields();
            for (Field f : fields) {
                if (f.isAnnotationPresent(annotationClass)) {
                    result.add(f);
                }
            }
            // 用作递归赋值（从 代理类 -> 真实类 的路径查找）
            beanClass = beanClass.getSuperclass();
        }

        return result;
    }

}
